package com.bblocks.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.bblocks.config.SpringContextUtils;
import com.bblocks.exception.ServiceException;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StringUtil {
    private static final String SEQ_MODEL = "ORDER_SEQ_MODEL";
	//经度
	public static final String LNG_PATTERN = "^[\\-\\+]?(0(\\.\\d{1,6})?|([1-9](\\d)?)(\\.\\d{1,6})?|1[0-7]\\d{1}(\\.\\d{1,6})?|180(\\.0{1,6})?)$";
	//纬度
	public static final String LAT_PATTERN = "^[\\-\\+]?((0|([1-8]\\d?))(\\.\\d{1,6})?|90(\\.0{1,6})?)$";

    public static final String base_char = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String base_num = "1234567890";

    /**
     * 获取指定长度的随机字符串
     * 范围0-9,a-z,A-Z
     *
     * @param length：指定字符串长度
     * @return -
     */
    public static String getRandomString(int length) {
        return getRandomString(length,false);
    }

    /**
     * 获取指定长度的随机字符串
     * 范围0-9,a-z,A-Z
     *
     * @param length 指定字符串长度
     * @param isNumber 是否纯数字
     * @return -
     */
    public static String getRandomString(int length,Boolean isNumber) {
        String base = base_char;
        if(isNumber){
            base = base_num;
        }
        return RandomUtil.randomString(base,length);
    }


    /**
     * 判断参数是否为空
     *
     * @param str 要判断的字符串
     * @return true:空   false:非空
     */
    public static boolean isNull(String... str) {
        boolean flag = false;
        for (String s : str) {
            if (s == null || "".equals(s.trim()) || "undefined".equals(s.trim()) || "null".equals(s.trim())) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 时间流编号
     *
     * @return 例:201912051412051111
     */
    public static String getTimeFlowNumber() {
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int rdn = getRandomNumber(1111, 9999);
        return date + rdn;
    }

    /**
     * 获取微信商户号
     *
     * @return 例:10000000000000201908271724205944
     */
    public static String getOutTradeNo() {
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int rdn = getRandomNumber(100000000, 999999999);
        return date + rdn+"000000001";
    }
    /**
     * 获取指定范围内的随机数
     *
     * @param min 最小数（包含）
     * @param max 最大数（包含）
     * @return
     */
    public static int getRandomNumber(int min, int max) {
        return RandomUtil.randomInt(min,max+1);
    }

    /**
     * 输出保留两位小数格式的价格
     *
     * @param price
     * @return 例: 15.1 -> 15.10
     */
    public static String getPriceFormat(Double price) {
        return new DecimalFormat("0.00").format(price);
    }

    /**
     * 删除数组中的指定值
     *
     * @param arr 数组
     * @param str 指定值
     * @return
     */
    public static String[] arrFilters(String[] arr, String str) {
        String[] res = null;
        if (arr != null && arr.length > 0) {
            List<String> tempList = Arrays.asList(arr);
            List<String> arrList = new ArrayList<>(tempList);
            Iterator<String> it = arrList.iterator();
            while (it.hasNext()) {
                String x = it.next();
                if (x.indexOf(str) != -1) {
                    it.remove();
                }
            }
            res = new String[arrList.size()];
            arrList.toArray(res);

            if(res.length>0){
                return res;
            }
        }
        return null;

    }


    /**
     * 是否包含字符串
     *
     * @param str 验证字符串
     * @param strs 字符串组
     * @return 包含返回true
     */
    public static boolean inStringIgnoreCase(String str, String... strs)
    {
        if (str != null && strs != null)
        {
            for (String s : strs)
            {
                if (str.equalsIgnoreCase(trim(s)))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 去空格
     */
    public static String trim(String str)
    {
        return (str == null ? "" : StrUtil.trim(str));
    }


    /**
     * 生成订单号（20210618 01(转成24进制) (9)+uid(3)+01234(5)），前缀如有需要自行添加
     * @param userId
     * @return
     */
    public static  String getOrderNumWithRandomNum(Long userId) {
        return getOrderNumWithRandomNum(userId,null);
    }

    public static  String getOrderNumWithRandomNum(Long userId,Integer serviceId) {
        return getOrderNum(userId,serviceId,1);
    }

	/**
	 * 生成订单号（serviceId(转成24进制)(实际长度可以为空)+20210618 01(转成24进制) (9)+uid(3)+01234(5)），前缀如有需要自行添加
     * 基于随机/顺序（按服务-serviceId）
	 * @param userId
     * @param serviceId 1-订单,9-支付单
     * @param type 1=随机（默认） ，2=顺序
	 * @return
	 */
	public static  String getOrderNum(Long userId,Integer serviceId,Integer type) {
		//serviceId(24进制)+2021061801(10)+uid(3)+01234(5)
		Date now = new Date();
		//时间（精确到小时） yyyyMMddHH=>yyyyMMdd +24进制（HH）
		String time = DateUtil.format(now, "yyyyMMdd") + RadixUtil.transRadix(DateUtil.format(now, "HH"),10,24)  ;

		//3位用户id
		int subStrLength = 3;
		String sUserId = String.valueOf(userId) ;
		int length = sUserId.length();
		String uidStr = "";
        if(userId != null) {
            if (length >= subStrLength) {//后3位
                uidStr = sUserId.substring(length - subStrLength, length);
            } else {
                uidStr = String.format("%0" + subStrLength + "d", userId.intValue());
            }
        }

		StringBuilder orderNum = new StringBuilder();
		if(serviceId != null)
			orderNum.append(RadixUtil.transRadix(serviceId.toString(),10,24));

        String randomNumeric = null;
        if(Integer.valueOf(2).equals(type)){
            RedisSequenceUtil sequenceUtil = SpringContextUtils.getBean(RedisSequenceUtil.class);

            randomNumeric = sequenceUtil.getNextSequence(serviceId != null? SEQ_MODEL+":"+serviceId:SEQ_MODEL,5,true);//顺序（按服务）
            orderNum.append(time).append(uidStr).append(randomNumeric);
        }else{
            //5位随机数
            randomNumeric = RandomUtil. randomNumbers(5);
            orderNum.append(time).append(uidStr).append(randomNumeric);
        }

		return orderNum.toString();
	}

    public static  String getOrderNumBySeq(Long userId,Integer serviceId) {
        //serviceId(24进制)+2021061801(10)+uid(3)+01234(5)
        Date now = new Date();
        //时间（精确到小时） yyyyMMddHH=>yyyyMMdd +24进制（HH）
        String time = DateUtil.format(now, "yyyyMMdd") + RadixUtil.transRadix(DateUtil.format(now, "HH"),10,24)  ;
        //5位随机数
        String randomNumeric = RandomUtil. randomNumbers(5);
        //3位用户id
        int subStrLength = 3;
        String sUserId = String.valueOf(userId) ;
        int length = sUserId.length();
        String uidStr;
        if (length >= subStrLength) {//后3位
            uidStr = sUserId.substring(length - subStrLength, length);
        } else {
            uidStr = String.format("%0" + subStrLength + "d",  userId.intValue());
        }


        StringBuilder orderNum = new StringBuilder();
        if(serviceId != null)
            orderNum.append(RadixUtil.transRadix(serviceId.toString(),10,24));

        orderNum.append(time).append(uidStr).append(randomNumeric);

        return orderNum.toString();
    }

	/**
	 * 2位数金额
	 * @param str
	 * @return
	 */
	public static boolean isAmount(String str) {
		Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
		Matcher match = pattern.matcher(str);
		return match.matches();
	}

	/**
	 * 是否经度
	 * @param lng
	 * @return
	 */
	public static boolean isLng(String lng) {
		Pattern p = Pattern.compile(LNG_PATTERN);
		return p.matcher(lng).matches();
	}

	/**
	 * 是否纬度
	 * @param lng
	 * @return
	 */
	public static boolean isLat(String lng) {
		Pattern p = Pattern.compile(LAT_PATTERN);
		return p.matcher(lng).matches();
	}

    /**
     * 组织url参数，为空返回“”
     * @param params value 为空则抛弃
     * @return a=1&b=2 。。。
     */
    public static String formUrlParamsStr(Map<String,Object> params){
        if(MapUtil.isEmpty(params)){
            return "";
        }else{
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if(entry.getValue() != null){
                    if(sb.length() > 0)
                        sb.append("&");
                    sb.append(entry.getKey() + "=" + entry.getValue());
                }
            }
            return sb.toString();
        }
    }

    /**
     * 格式url参数，形成Map
     * @param paramsStr a=1&b=2&c=3
     * @return
     */
    public static Map<String,String> parseUrlParamsStr(String paramsStr){
        if(StrUtil.isEmpty(paramsStr)){
            return null;
        }else{
            Map<String,String> result = new HashMap<>();
            List<String> oneParams = Splitter.on("&").splitToList(paramsStr);

            for(String oneParam : oneParams){
                Pair<String,String> one = parseUrlParamStr(oneParam);
                if(one != null){
                    result.put(one.getKey(),one.getValue());
                }
            }
            return result;
        }
    }

    /**
     * 提取url一对参数（a=1），不满足a=1的情况下将返回null
     * @param paramStr
     * @return
     */
    protected static Pair<String,String> parseUrlParamStr(String paramStr){
        if(StrUtil.isEmpty(paramStr)){
            return null;
        }else{
            List<String> oneParam = Splitter.on("=").splitToList(paramStr);
            if(oneParam.size() == 2){
                return Pair.of(oneParam.get(0),oneParam.get(1));
            }else
                return null;
        }
    }

    public  static void main(String[] args){
		System.out.println((getOrderNumWithRandomNum(1L,1)));

		System.out.println((getOrderNumWithRandomNum(1L,12)));

		System.out.println((getOrderNumWithRandomNum(1L,null)));

		System.out.println(isAmount("0.1"));
		System.out.println(isAmount("0.01"));


		Pattern p = Pattern.compile(LNG_PATTERN);
System.out.println(p.matcher("181").matches());
System.out.println(p.matcher("180.001").matches());
System.out.println(p.matcher("180.0000").matches());
		double b =1.0;
		String s = Convert.numberToChinese(b, false);
		System.out.println(s);

		 s = Convert.numberToChinese(b, true);
		System.out.println(s);
	}

}
